﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using InfoJetSoft.Service;
using Microsoft.SharePoint;
using System.Xml;
using System.Xml.XPath;
using System.Text;
using Microsoft.SharePoint.Workflow;
using ServBus.ListForm2010.Utility;
using ServBus.ListForm2010.Extension;
using Microsoft.SharePoint.WebControls;
using ServBus.ListForm2010.License;
using Microsoft.SharePoint.Workflow;
using System.Web;

namespace ServBus.ListForm2010.Layouts.ListForm2010
{
    public partial class ListFormWFInner : LayoutsPageBase
    {
        #region Parameters

        private string _webpartMode = string.Empty;//"NEW";
        private string _siteName;//"http://win-3ststb2hjp7";
        private Guid _webName;//"Test";
        private string _listId = "";//"test";
        private string _ctypeId = "";
        private string _itemId = "";//string.Empty;
        private string _viewId = "";//string.Empty;
        private string _xsnLocation = "";
        private string _errorMsg = "";
        //private  string InfojetServiceAction = "/_layouts/ListForm2010/xdoc.aspx";
        private string _ctypeName = "";
        private string _MlistId = "";
        private string _MItemId = "";
        private string _HlistId = "";
        private string _WInstanceId = "";

        private readonly Dictionary<string, Dictionary<int, string>> SItemsId = new Dictionary<string, Dictionary<int, string>>();

        private XmlNamespaceManager _xNameSpace;

        #endregion

        private void errorLog(Exception ex, bool internalError)
        {

            if (internalError)
            {
                errorPanel.Visible = true;
            }
            ////else
            {
#if DEBUG
                errorPanel.Visible = false;
                LTException.Text = ex.Message;
                LTException.Visible = true;
#else
                LTException.Text = ex.Message;
                LTException.Visible = false;
#endif
            }
            ErrorLog.Write("ListFormWFInner" + "\r\n" + Request.Url + "\r\n" + ex.Message + "\r\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
        }

        private void Notice_RefreshXSN()
        {
            refreshPanel.Visible = true;
        }

        #region Page Method

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    Activations activations = new Activations(SPContext.Current.Site.WebApplication);
                    if (!activations.IsActivationValid(SPContext.Current.Web, out _errorMsg))
                    {
                        errorLog(new Exception(_errorMsg), false);
                    }
                    else
                    {
                        //InfoJetService.ServiceAction = InfojetServiceAction;
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableRichText(true);
                        InfoJetSoft.Service.Util.ConfigUtil.EditRichTextOnFocus = true;
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableFormFieldsCache(true);
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnablePlaceholderUI(true);
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableMasterDetailsPopup(true);

                        _webpartMode = Page.Request["wpMode"].ToUpper();
                        _listId = Page.Request["listId"];
                        _ctypeId = Page.Request["ctype"];
                        //viewId = Page.Request["view"];
                        _siteName = SPContext.Current.Site.Url;

                        _webName = SPContext.Current.Web.ID;

                        _xNameSpace = new XmlNamespaceManager(new NameTable());
                        _xNameSpace.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
                        _xNameSpace.AddNamespace("tns", "http://tempuri.org/");
                        _xNameSpace.AddNamespace("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
                        if (Page.IsPostBack) return;
                        _itemId = Page.Request["itemId"];
                        GenerateEditForm();
                    }
                }
            }
            catch (Exception ex)
            {
                errorLog(ex, true);
            }
        }

        protected void DeleteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(_siteName))
                    {
                        using (SPWeb web = site.OpenWeb(_webName))
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList list = web.Lists[new Guid(_listId)];
                            int itemId = Convert.ToInt32(_itemId);
                            SPListItem item = list.GetItemById(itemId);
                            item.Recycle();
                        }
                    }
                });
                Response.Write("<script type='text/javascript'>parent.window.frameElement.commitPopup('Operation Successful!')</script>");

            }
            catch (Exception ex)
            {
                errorLog(ex, true);
            }
        }
        #endregion

        #region Private Method

        private void GenerateEditForm()
        {
            SItemsId.Clear();
            string xmlTemplate = GetXMLTemplate().Xml;
            if (xmlTemplate != string.Empty)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xmlTemplate);

                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(_siteName))
                    {
                        using (SPWeb web = site.OpenWeb(_webName))
                        {
                            SPList list = web.Lists[new Guid(_listId)];
                            SPContentTypeId contentTypeId = new SPContentTypeId(_ctypeId.ToLower());
                            _ctypeName = list.ContentTypes[contentTypeId].Name;
                            int itemId = Convert.ToInt32(_itemId);
                            SPListItem item = list.GetItemById(itemId);

                            try
                            {
                                XmlNode tNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:Task", _xNameSpace);
                                foreach (XmlNode xNode in tNode.ChildNodes)
                                {
                                    SetListFieldsValue(xNode, list, item);
                                }
                            }
                            catch (Exception)
                            {
                                Notice_RefreshXSN();
                            }

                            _MlistId = Convert.ToString(item[SPBuiltInFieldId.WorkflowListId]);
                            _MItemId = Convert.ToString(item[SPBuiltInFieldId.WorkflowItemId]);
                            _WInstanceId = Convert.ToString(item[SPBuiltInFieldId.WorkflowInstanceID]);

                            SPList mList = web.Lists[new Guid(_MlistId)];
                            int mItemId = Convert.ToInt32(_MItemId);
                            SPListItem mitem = mList.GetItemById(mItemId);
                            _ctypeName = "";
                            XmlNode mNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:RelatedContent", _xNameSpace);
                            foreach (XmlNode xNode in mNode.ChildNodes)
                            {
                                SetListFieldsReadOnlyValue(xNode, mList, mitem);
                            }

                            SPWorkflow spWF = new SPWorkflow(item, new Guid(_WInstanceId));
                            _HlistId = Convert.ToString(spWF.HistoryListId);
                            SPList hList = web.Lists[new Guid(_HlistId)];
                            _ctypeName = hList.ContentTypes[0].Name;
                            XmlNode wNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:WorkflowHistory", _xNameSpace);
                            SetLkpFormValue(wNode, mItemId);

                            InfoJetContext ijCtx = new InfoJetContext
                            {
                                InlineFileStorage = new InlineFileStorage(),
                                ExportFileStorage = new ExportFileStorage()
                            };

                            RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                            ijCtx.RelativeUrlResolver = resolver;
                            if (!string.IsNullOrEmpty(_viewId))
                            {
                                ijCtx.ViewName = _viewId;
                            }

                            //Start:14-2-26 Attachments Feature add
                            string attachmentsPath = "/dfs:myFields/dfs:dataFields/tns:RelatedContent/tns:" + mList.Title + "__Attachments";
                            string[] attachmentsUrlStrings = new string[mitem.Attachments.Count];
                            for (int i = 0; i < mitem.Attachments.Count; i++)
                            {
                                attachmentsUrlStrings[i] = mitem.Attachments.UrlPrefix + mitem.Attachments[i];
                            }
                            ijCtx.SetListAttachments(attachmentsPath, attachmentsUrlStrings);
                            //ijCtx.IsListAttachmentsReadonly = true;
                            //End:14-2-26 Attachments Feature add
                            InfoJetForm editForm = InfoJetService.BuildFormByXML(Context, ijCtx, _xsnLocation, xDoc.OuterXml);
                            xDocViewInner.Text = editForm.Xhtml;
                        }
                    }
                });
            }
        }

        private Dictionary<string, string> GetViewConfigItem(SPWeb web, string mListID, string mContentTypeID)
        {
            Dictionary<string, string> views = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(mListID) || string.IsNullOrEmpty(mContentTypeID)) return views;
            try
            {
                SPList configList = web.Lists[Constants.LookupForm_Config_NAME];
                SPQuery query = new SPQuery
                {
                    Query =
                        "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + mListID +
                        "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + mContentTypeID +
                        "</Value></Eq></And></Where>"
                };
                SPListItemCollection items = configList.GetItems(query);
                if (items.Count > 0)
                {
                    string dispView = Convert.ToString(items[0]["mDispView"]);
                    string editView = Convert.ToString(items[0]["mEditView"]);
                    string newView = Convert.ToString(items[0]["mNewView"]);

                    if (!string.IsNullOrEmpty(dispView))
                    {
                        views.Add("DISP", dispView);
                        views.Add("EDIT", editView);
                        views.Add("NEW", newView);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return views;
        }

        private bool RegisterXSNTemplate()
        {
            Guid xsnId;

            byte[] xsnContent;

            bool succeed = false;
            InfoJetService.License(Constants.InfoJetLicense);



            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(_siteName))
                {
                    using (SPWeb web = site.OpenWeb(_webName))
                    {
                        SPList list = web.Lists[new Guid(_listId)];
                        SPContentTypeId contentTypeId = new SPContentTypeId(_ctypeId.ToLower());
                        SPContentType cType = list.ContentTypes[contentTypeId];
                        _xsnLocation = web.Url + "/" + cType.ResourceFolder.Url + "/template.xsn";

                        SPFile file = web.GetFile(_xsnLocation);
                        xsnContent = file.OpenBinary();
                        xsnId = file.UniqueId;


                        if (xsnContent == null)
                        {
                            succeed = false;
                        }
                        else
                        {
                            string md5 = CryptoUtility.ComputeMD5(xsnContent);
                            if (InfoJetService.GetMD5(_xsnLocation) == md5)
                            {
                                succeed = true;
                            }
                            else
                            {
                                InfoJetContext ijCtx = new InfoJetContext();
                                ijCtx.Variables.Add("InfoBus_XsnId", xsnId.ToString());
                                ijCtx.ResourceFileStorage = new ResourceFileStorage(web);
                                ijCtx.InlineFileStorage = new InlineFileStorage();
                                succeed = InfoJetService.RegisterWithMD5(Context, ijCtx, _xsnLocation, xsnContent, "/_layouts/ListForm2010/", md5);
                            }
                        }
                        Dictionary<string, string> views = GetViewConfigItem(web, Convert.ToString(list.ID), Convert.ToString(cType.Id));
                        _webpartMode = Page.Request["wpMode"].ToUpper();
                        if (views.ContainsKey(_webpartMode))
                        {
                            _viewId = views[_webpartMode];
                        }
                    }
                }
            });
            return succeed;
        }

        private InfoJetForm GetXMLTemplate()
        {
            if (RegisterXSNTemplate())
            {

                InfoJetContext ijCtx = new InfoJetContext
                {
                    InlineFileStorage = new InlineFileStorage(),
                    ExportFileStorage = new ExportFileStorage()
                };
                RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                ijCtx.RelativeUrlResolver = resolver;
                //if (!string.IsNullOrEmpty(viewId))
                //{
                //    ijCtx.ViewName = viewId;
                //}
                InfoJetForm newForm = InfoJetService.BuildFormByTemplate(Context, _xsnLocation, ijCtx);
                return newForm;
            }
            return null;
        }

        private void SetListFieldsValue(XmlNode xNode, SPList plist, SPListItem p_Item)
        {
            if (xNode.HasChildNodes)
            {
                foreach (XmlNode cXNode in xNode.ChildNodes)
                {
                    SetListFieldsValue(cXNode, plist, p_Item);
                }
            }
            SetValue(xNode.CreateNavigator(), plist, p_Item);
        }

        private void SetListFieldsReadOnlyValue(XmlNode xNode, SPList plist, SPListItem p_Item)
        {
            if (xNode.HasChildNodes)
            {
                foreach (XmlNode cXNode in xNode.ChildNodes)
                {
                    SetListFieldsValue(cXNode, plist, p_Item);
                }
            }
            SetReadOnlyValue(xNode.CreateNavigator(), plist, p_Item);
        }

        private void SetLkpFormValue(XmlNode xNode, int itemId)
        {
            XmlNode node = xNode;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(_siteName))
                {
                    using (SPWeb web = site.OpenWeb(_webName))
                    {
                        web.AllowUnsafeUpdates = true;
                        if (node.Attributes != null)
                        {
                            SPList mList = web.Lists[new Guid(_listId)];
                            SPList hList = web.Lists[new Guid(_HlistId)];
                            List<XmlNode> addSContentTypeNode = new List<XmlNode>();
                            XmlNode sContentTypeNode = node;
                            if (sContentTypeNode.Attributes != null)
                            {
                                SPListItemCollection resultItems = GetLkpSubItems(hList, _WInstanceId, itemId);
                                foreach (SPListItem sItem in resultItems)
                                {
                                    XmlNode sItemNode = sContentTypeNode.Clone();
                                    sItemNode.CreateNavigator();
                                    //sItemNav.CreateAttribute("", "ItemID", "", sItem.ID.ToString());
                                    if (sItemNode.Attributes != null)
                                        sItemNode.Attributes["Item_ID"].Value = sItem.ID.ToString(CultureInfo.InvariantCulture);

                                    foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                                    {
                                        SetReadOnlyValue(sFieldNode.CreateNavigator(), hList, sItem);
                                    }

                                    //XPathNavigator listNav = rootNav.SelectSingleNode(string.Format("/dfs:myFields/dfs:dataFields/tns:mainForm/tns:SubForms/tns:{0}", listNode.LocalName), xNameSpace);
                                    //listNav.AppendChild(sItemNav);
                                    addSContentTypeNode.Add(sItemNode);
                                }
                            }

                            node.RemoveAll();
                            XPathNavigator listNav = node.CreateNavigator();
                            listNav.CreateAttribute("", "List_ID", "", hList.ID.ToString());
                            foreach (XmlNode addNode in addSContentTypeNode)
                            {
                                node.ParentNode.InsertAfter(addNode, node);
                            }
                            node.ParentNode.RemoveChild(node);
                        }
                    }
                }
            });
        }

        private SPListItemCollection GetLkpSubItems(SPList hList, string instanceId, int itemId)
        {
            SPQuery query = new SPQuery
            {
                Query = string.Format("<Where><And><Eq><FieldRef Name='{0}'/> <Value Type='Text'>{1}</Value></Eq>"
                + "<Eq><FieldRef Name='{2}' /><Value Type='Text'>{3}</Value></Eq></And></Where>",
                    "WorkflowInstance", instanceId, "Item", itemId)
            };

            return hList.GetItems(query);
        }

        private SPField GetLkpField(SPList mList, SPList sList, string ctName)
        {
            SPField lkpField = null;
            SPContentType ctype = sList.ContentTypes[ctName];
            //Find lkp Field
            foreach (SPField sField in ctype.Fields)
            {
                if (sField.Type.Equals(SPFieldType.Lookup))
                {
                    SPFieldLookup sLkpField = (SPFieldLookup)sField;
                    Guid sLkpID = new Guid(sLkpField.LookupList);
                    if (sLkpID.Equals(mList.ID))
                    {
                        lkpField = sLkpField;
                        break;
                    }
                }
            }

            return lkpField;
        }

        private void SetValue(XPathNavigator p_XPathNav, SPList plist, SPListItem p_Item)
        {
            if (p_XPathNav != null)
            {
                string uniquePrefix = string.Format("{0}_{1}_", plist.Title, _ctypeName).Replace(" ", "_");
                uniquePrefix = ServBus.ListForm2010.Common.WFXSNOperator.FieldHelper.GetUniquefieldName(uniquePrefix);
                string localName = p_XPathNav.LocalName.Replace(uniquePrefix, "");
                
                //begin looping through the nodes
                if (!string.IsNullOrEmpty(localName))
                {
                    #region Set Value

                    string mFieldInternalName = localName;
                    if (plist.Fields.ContainsField(mFieldInternalName))
                    {
                        SPField mField = plist.Fields.GetField(mFieldInternalName);

                        string mFieldValue = GetFormValueFromField(mField, p_Item);

                        if (string.IsNullOrEmpty(mFieldValue))
                        {
                            return;
                        }

                        //根据不同的Field类型，表单对应不同的数据类型，这里需要判断
                        switch (mField.Type)
                        {
                            case SPFieldType.Number:
                                DeleteNil(p_XPathNav);
                                p_XPathNav.SetValue(mFieldValue);
                                break;

                            case SPFieldType.DateTime:
                                DeleteNil(p_XPathNav);
                                SPFieldDateTime dateTimeField = (SPFieldDateTime)mField;
                                //DateOnly
                                if (dateTimeField.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
                                {
                                    DateTime dt = DateTime.Parse(mFieldValue);
                                    p_XPathNav.SetValue(dt.Date.ToString("yyyy-MM-dd"));
                                }
                                else
                                {
                                    DateTime dt = DateTime.Parse(mFieldValue);
                                    p_XPathNav.SetValue(dt.Date.ToString("s"));
                                }
                                break;

                            case SPFieldType.User:
                                //if (p_xPathNav.InnerXml == "")
                                //{
                                //    return;
                                //}
                                InsertToUserType(p_Item, mField.Id, p_XPathNav);
                                break;

                            case SPFieldType.MultiChoice:
                                InsertIntoCheckBoxType(mFieldValue, p_XPathNav, p_XPathNav.LocalName);
                                break;

                            case SPFieldType.Note:
                                SPFieldMultiLineText noteField = (SPFieldMultiLineText)mField;
                                if (noteField.RichText)
                                {
                                    p_XPathNav.InnerXml = mFieldValue;
                                }
                                else
                                {
                                    p_XPathNav.InnerXml = noteField.GetFieldValueAsText(p_Item[mFieldInternalName]);
                                }
                                break;
                            case SPFieldType.Lookup:
                                p_XPathNav.SetValue(mFieldValue);
                                break;

                            default:
                                p_XPathNav.SetValue(mFieldValue);
                                break;
                        }
                    }
                    #endregion
                }
            }
        }

        private void SetReadOnlyValue(XPathNavigator p_XPathNav, SPList plist, SPListItem p_Item)
        {
            if (p_XPathNav != null)
            {
                string uniquePrefix = string.Format("{0}_{1}_", plist.Title, _ctypeName).Replace(" ", "_");
                uniquePrefix = ServBus.ListForm2010.Common.WFXSNOperator.FieldHelper.GetUniquefieldName(uniquePrefix);
                string localName = p_XPathNav.LocalName.Replace(uniquePrefix, "");

                //begin looping through the nodes
                if (!string.IsNullOrEmpty(localName))
                {
                    #region Set Value

                    string mFieldInternalName = localName;
                    if (plist.Fields.ContainsField(mFieldInternalName))
                    {
                        if (mFieldInternalName.Equals("LinkFilename"))
                        {
                            p_XPathNav.SetValue((string)p_Item[SPBuiltInFieldId.EncodedAbsUrl]);
                        }
                        else if (mFieldInternalName.Equals("LinkTitle"))
                        {
                            string displayFormUrl = plist.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + p_Item.ID;
                            p_XPathNav.SetValue(plist.ParentWeb.Url + "/" + displayFormUrl);
                        }
                        else
                        {
                            SPField mField = plist.Fields.GetField(mFieldInternalName);

                            string mFieldValue = GetFormValueFromField(mField, p_Item);

                            if (string.IsNullOrEmpty(mFieldValue))
                            {
                                return;
                            }

                            if (mField.Type.Equals(SPFieldType.WorkflowEventType))
                            {
                                int eventValue = Convert.ToInt32(mField.GetFieldValueAsText(p_Item[mField.Title]));
                                p_XPathNav.SetValue(Enum.GetName(typeof(SPWorkflowHistoryEventType), eventValue));
                            }
                            else
                            {
                                p_XPathNav.SetValue(mField.GetFieldValueAsText(p_Item[mField.Title]));
                            }
                        }
                    }
                    #endregion
                }
            }
        }

        /// <summary>
        /// 从列表的Field中获取值填充到InfoPath节点中
        /// </summary>
        /// <param name="p_Field"></param>
        /// <param name="p_Item"></param>
        /// <returns></returns>
        private string GetFormValueFromField(SPField p_Field, SPListItem p_Item)
        {

            string mStrValue = string.Empty;
            try
            {

                if (p_Item[p_Field.Id] == null)
                {
                    return mStrValue;
                }
                else if (string.IsNullOrEmpty(Convert.ToString(p_Item[p_Field.Id])))
                {
                    return mStrValue;
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                return mStrValue;
            }


            switch (p_Field.Type)
            {
                case SPFieldType.Lookup:
                    string mLookupValue = p_Item[p_Field.Id].ToString();

                    int tIndex = mLookupValue.IndexOf("#", StringComparison.Ordinal);
                    mStrValue = mLookupValue.Substring(0, tIndex - 1);
                    //m_str_value = m_lookup_value;                   //读取数据时出错。TO DO...目前先临时改回来
                    break;

                case SPFieldType.DateTime:
                    DateTime mTime = (DateTime)p_Item[p_Field.Id];
                    mStrValue = Convert.ToString(mTime);
                    break;

                case SPFieldType.Note:
                    //Obsolete

                    mStrValue = Convert.ToString(p_Item[p_Field.Id]);
                    mStrValue = GetMulitTextString(mStrValue);
                    break;

                case SPFieldType.URL:
                    SPFieldUrlValue urlValue = new SPFieldUrlValue(Convert.ToString(p_Item[p_Field.Id]));
                    mStrValue = urlValue.Url;
                    break;

                case SPFieldType.Boolean:
                    bool booleanField = Convert.ToBoolean(p_Item[p_Field.Id]);
                    mStrValue = booleanField ? "true" : "false";
                    break;

                default:
                    mStrValue = Convert.ToString(p_Item[p_Field.Id]);
                    break;
            }
            return mStrValue;
        }

        /// <summary>
        /// 架构验证发现无数据类型错误的解决方案，目前只用于数字类型
        /// </summary>
        /// <param name="node">当前节点</param>
        private void DeleteNil(XPathNavigator node)
        {
            if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
            {
                node.DeleteSelf();
            }
        }

        /// <summary>
        /// 插入用户信息到pc:Person类型的节点中
        /// </summary>
        /// <param name="fieldTitle"></param>
        /// <param name="xPathNav"></param>
        /// <param name="item"></param>
        private void InsertToUserType(SPListItem item, Guid fieldId, XPathNavigator xPathNav)
        {
            string pcValue;
            if (xPathNav.HasChildren)
            {
                xPathNav.SetValue("");
            }
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(_siteName))
                {
                    using (site.OpenWeb(_webName))
                    {
                        try
                        {
                            SPFieldUser userField = (SPFieldUser)item.Fields[fieldId];
                            SPFieldUserValue userValue = (SPFieldUserValue)userField.GetFieldValue(Convert.ToString(item[fieldId]));
                            SPUser user = userValue.User;
                            pcValue = "<pc:Person><pc:DisplayName>" + user.Name + "</pc:DisplayName><pc:AccountId>" + user.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                            xPathNav.AppendChild(pcValue);

                        }
                        catch
                        {
                            SPFieldUserValueCollection userValues = item[fieldId] as SPFieldUserValueCollection;

                            if (userValues != null)
                                foreach (SPFieldUserValue userValue in userValues)
                                {
                                    SPUser user = userValue.User;
                                    if (user != null)
                                    {
                                        pcValue = "<pc:Person><pc:DisplayName>" + user.Name + "</pc:DisplayName><pc:AccountId>" + user.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                                        xPathNav.AppendChild(pcValue);
                                    }
                                    else
                                    {
                                        SPGroup group = Web.Groups.GetByID(userValue.LookupId);
                                        pcValue = "<pc:Person><pc:DisplayName>" + group.Name + "</pc:DisplayName><pc:AccountId>" + group.LoginName + "</pc:AccountId><pc:AccountType>Group</pc:AccountType></pc:Person>";
                                        xPathNav.AppendChild(pcValue);
                                    }
                                }
                        }
                    }
                }
            });

        }

        private void InsertIntoCheckBoxType(string fieldValue, XPathNavigator xPathNav, string fieldName)
        {
            fieldName = fieldName + "_1";
            SPFieldMultiChoiceValue choiceValue = new SPFieldMultiChoiceValue(fieldValue);

            string myNamespace = "xmlns:my=\"http://tempuri.org/\"";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < choiceValue.Count; i++)
            {
                sb.AppendFormat("<tns:{0} {2}>{1}</tns:{0}>", fieldName, choiceValue[i], myNamespace);
            }
            xPathNav.AppendChild(sb.ToString());
        }

        private string GetMulitTextString(string p_Field_String)
        {
            string mComment;
            try
            {

                XmlDocument mDoc = new XmlDocument();
                mDoc.LoadXml(p_Field_String);

                mComment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + mDoc.InnerXml + "</div>";

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mComment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + p_Field_String + "</div>";
            }

            return mComment;
        }

        #endregion
    }
}
